package com.lxw.report.meta.converter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lxw
 * @time 2022/1/10 16:00
 */
@Component
public class StringToDateConverter implements Converter<String,Date> {

    Logger logger= LoggerFactory.getLogger(StringToDateConverter.class);

    SimpleDateFormat simpleDateFormat1=new SimpleDateFormat("yyyy-MM");
    SimpleDateFormat simpleDateFormat2=new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat simpleDateFormat3=new SimpleDateFormat("yyyy-MM-dd HH");
    SimpleDateFormat simpleDateFormat4=new SimpleDateFormat("yyyy-MM-dd HH:mm");
    SimpleDateFormat simpleDateFormat5=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override
    public Date convert(String source) {
        if (source == null || source.trim().equals("")) {
            return null;
        }
        Date result = null;
        String originalValue = source.trim();
        if (source.matches("^\\d{4}-\\d{1,2}$")) {
            return parseDate(source, simpleDateFormat1);
        } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
            return parseDate(source, simpleDateFormat2);
        } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}$")) {
            return parseDate(source, simpleDateFormat3);
        } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) {
            return parseDate(source, simpleDateFormat4);
        } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
            return parseDate(source, simpleDateFormat5);
        } else if (originalValue.matches("^\\d{1,13}$")) {
            try {
                long timeStamp = Long.parseLong(originalValue);
                if (originalValue.length() > 10) {
                    result = new Date(timeStamp);
                } else {
                    result = new Date(1000L * timeStamp);
                }
            } catch (Exception e) {
                result = null;
                logger.error("字符串转日期出错：{}",originalValue);
            }
        } else {
            result = null;
        }

        return result;
    }

    /**
     * 格式化日期
     *
     * @param dateStr    String 字符型日期
     * @param dateFormat 日期格式化器
     * @return Date 日期
     */
    public Date parseDate(String dateStr, DateFormat dateFormat){
        Date date = null;
        try {
            date = dateFormat.parse(dateStr);
        } catch (Exception e) {
            logger.error("字符串转日期出错：{}",dateStr);
        }
        return date;
    }
}
